<?php
/** 自定义函数
 * Created by PhpStorm.
 * User: user
 * Date: 2019/6/11
 * Time: 16:43
 */


//xml数据转化成数组
if (!function_exists('xml_to_array')) {
    /**
     * @param $xml_str
     * @return array
     */
    function xml_to_array($xml_str)
    {
        $str = '';
        $new_arr = [];
        $xml_obj = simplexml_load_string($xml_str);
        //拼接成a=1&b=2形式字符串
        foreach ($xml_obj->children() as $child) {
            $str .= $child->getName() . '=' . $child . '&';
        }
        //去掉最后一位的&字符
        $str = substr($str,0,-1);
        $arr = explode('&',$str);

        foreach($arr as $value){
            $tmp = explode('=',$value);
            if($tmp[1]){//只返回有值的key
                $new_arr[$tmp[0]] = $tmp[1];
            }
        }
        return $new_arr;
    }
}

if(!function_exists('curl_post')){
    function curl_post($url,array $post_data,$data_type='json'){
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        if($data_type == 'json'){
            $post_data = json_encode($post_data,JSON_UNESCAPED_UNICODE);
        }elseif($data_type == 'str'){
            $post_data = http_build_query($post_data);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        // 3. 执行并获结果
        $output = curl_exec($ch);
        if($output === FALSE ){
            echo "CURL Error:".curl_error($ch);
        }
        // 4. 释放curl句柄
        curl_close($ch);

        return $output;
    }
}


if(!function_exists('curl_get')){
    function curl_get($url){
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 3. 执行并获结果
        $output = curl_exec($ch);
        if($output === FALSE ){
            echo "CURL Error:".curl_error($ch);
        }
        // 4. 释放curl句柄
        curl_close($ch);

        return $output;
    }
}

//返回随机字符串
if(!function_exists('random_str')){
    function random_str($length = 16){
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $return = '';
        for ($i=0;$i<$length;$i++){
            $return .= $str[rand(0,51)];
        }
        return $return;
    }
}